package com.glory.good_dark.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.good_dark.R;
import com.glory.good_dark.adapter.DefectListAdapter;
import com.glory.good_dark.application.App;
import com.glory.good_dark.entity.EqpInfoEntity;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author yi.zhang
 * @date 2019/6/26
 * @desc 批次结束界面
 */
public class BatchWorkEndActivity extends BaseProjectActivity implements TextWatcher {
    @BindView(R.id.lot_Txt)
    TextView lotTxt;
    @BindView(R.id.startTime_Txt)
    TextView startTimeTxt;
    @BindView(R.id.inputNum_Txt)
    TextView inputNumTxt;
    @BindView(R.id.qualified_Txt)
    TextView qualifiedTxt;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.lot_Ly)
    LinearLayout lotLy;
    @BindView(R.id.tank_But)
    Button tankBut;
    @BindView(R.id.emptyFrame_Eit)
    FreeUI_ClearEditText emptyFrameEit;
    @BindView(R.id.emptyFrame_Lay)
    LinearLayout emptyFrameLay;
    @BindView(R.id.EQPID_Txt)
    TextView EQPIDTxt;
    @BindView(R.id.defectNum_txt)
    TextView defectNumTxt;
    @BindView(R.id.etOutputNum)
    TextView etOutputNum;
    @BindView(R.id.rvDefect)
    RecyclerView rvDefect;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.tvProcess)
    TextView tvProcess;
    private EqpInfoEntity eqpInfoEntity;
    private DefectListAdapter defectListAdapter;
    private int PROCESS_TRACK_OUT_CRR = 1;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_batchworkend;
    }

    @Override
    protected void initView() {
        EQPIDTxt.setText(App.EQPID);
        etOutputNum.addTextChangedListener(this);
        initRecyclerView(rvDefect, this);
        defectListAdapter = new DefectListAdapter(null,defectNumTxt);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvDefect.setAdapter(defectListAdapter);

    }

    @Override
    protected void initData() {
//        String ss = "{\n" +
//                "    \"data\":{\n" +
//                "        \"HEADER\":{\n" +
//                "            \"MACHINENAME\":\"PDA-MT9001\",\n" +
//                "            \"MESSAGENAME\":\"PDARptRunInfo\",\n" +
//                "            \"TRANSACTIONID\":\"c5e5e318-389d-4c39-b914-e4c10ba519d4\",\n" +
//                "            \"EVENTTIME\":\"2019-03-16 16:28:59.585\"\n" +
//                "        },\n" +
//                "        \"BODY\":{\n" +
//                "            \"LOT_ID\":\"TS00001\",\n" +
//                "            \"OPERATOR\":\"admin\",\n" +
//                "            \"PROCESS\":\"GX001\",\n" +
//                "            \"START_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"END_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"TRACKIN_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"TRACKOUT_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"ABNOMAL_TOTAL_QUANTITY\":20,\n" +
//                "            \"PRODUCTION_TOTAL_QUANTITY\":2100,\n" +
//                "            \"FLOW_CARD_ID\":\"AAA\",\n" +
//                "            \"EQP_NO\":\"LC128\",\n" +
//                "            \"TRANSID\":102,\n" +
//                "            \"EQP_CAPA\":\"   \",\n" +
//                "            \"RECIPENAME\":\"AD125\",\n" +
//                "            \"NUMBER_OF_GOOD_PARES\":2000,\n" +
//                "            \"DESCRIPTION\":\"ms\",\n" +
//                "            \"CREATOR\":\"AD125\",\n" +
//                "            \"UPDATOR\":\"TS00001\",\n" +
//                "            \"CREATED_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"UPDATED_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"EAP_ID\":333,\n" +
//                "            \"REJECTS_QT_LIST\":[\n" +
//                "                {\n" +
//                "                    \"REJECTS_CODE\":\"4KUAISU1\",\n" +
//                "                    \"QT_1\":100,\n" +
//                "                    \"QT_2\":0\n" +
//                "                }\n" +
//                "            ],\n" +
//                "            \"LOLD_CODE_LIST\":[\n" +
//                "                {\n" +
//                "                    \"HOLD_ID\":\"4KUAISU1\",\n" +
//                "                    \"HOLD_DESCRIPTION\":\"描述\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"HOLD_ID\":\"33UAISU1\",\n" +
//                "                    \"HOLD_DESCRIPTION\":\"说明\"\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        },\n" +
//                "        \"Return\":{\n" +
//                "            \"RETURNCODE\":\"0\",\n" +
//                "            \"RETURNMESSAGE\":\"\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//        BaseEntity<EqpInfoEntity> bean = (new Gson()).fromJson(ss, new TypeToken<BaseEntity<EqpInfoEntity>>() {
//        }.getType());
//        eqpInfoEntity = bean.getData().getBody();
//        fillData();
        getInfo();
    }

    private void getInfo() {

        FreeUI_EntityCallBack<BaseEntity<EqpInfoEntity>> callBack2 = new FreeUI_DialogEntityCallBack<BaseEntity<EqpInfoEntity>>
                (new TypeToken<BaseEntity<EqpInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<EqpInfoEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
                    eqpInfoEntity = response.body().getData().getBody();
                    if (eqpInfoEntity.getLOT_ID().equals("")) {
                        showToast("无批次信息", false);
                    } else {
                        fillData();
                    }
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<EqpInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDARptRunInfo");
            }
        };
        JsonObject jsonObject2 = new JsonObject();
        jsonObject2.addProperty("EQP_ID", App.EQPID);
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack2, "PDARptRunInfo", jsonObject2);
    }

    private void fillData() {
        List<String> holdCode = new ArrayList<>();
        lotTxt.setText(eqpInfoEntity.getLOT_ID());
        startTimeTxt.setText(eqpInfoEntity.getSTART_TIME());
        tvProcess.setText(eqpInfoEntity.getTRACKOUT_CRR_ID());
        defectListAdapter.setNewData(eqpInfoEntity.getREJECTS_QT_LIST());
        if (eqpInfoEntity.getLOLD_CODE_LIST().size() > 0) {
            for (EqpInfoEntity.HoldCode str : eqpInfoEntity.getLOLD_CODE_LIST()){
                holdCode.add(str.getHOLD_ID() + "/" + str.getHOLD_DESCRIPTION());
            }
        }
        defectListAdapter.setDefectList(holdCode);
        defectListAdapter.setTotalNum(eqpInfoEntity.getPRODUCTION_TOTAL_QUANTITY());
        inputNumTxt.setText(String.valueOf(eqpInfoEntity.getPRODUCTION_TOTAL_QUANTITY()));
        defectNumTxt.setText(String.valueOf(eqpInfoEntity.getABNOMAL_TOTAL_QUANTITY()));
        etOutputNum.setText(String.valueOf(eqpInfoEntity.getNUMBER_OF_GOOD_PARES()));

    }

    private void submit() {
        FreeUI_EntityCallBack<BaseEntity<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<JSONObject>>
                (new TypeToken<BaseEntity<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<JSONObject>> response) {
                if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
//                    showToast("结束作业成功", true);
                    showConfirmDialog(BatchWorkEndActivity.this,"结束作业成功");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDATrankOut");
            }
        };
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EAP_ID", eqpInfoEntity.getEAP_ID());
        jsonObject.addProperty("TRACKOUT_CRR_ID",tvProcess.getText().toString());
        jsonObject.addProperty("ABNOMAL_TOTAL_QUANTITY", Integer.parseInt(defectNumTxt.getText().toString().trim()));
        jsonObject.add("REJECTS_QT_LIST",new JsonParser().parse(new Gson().toJson(defectListAdapter.getData())).getAsJsonArray());
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDATrankOut", jsonObject);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次结束操作");
        freeUI_titleView.setRightListener("结束作业", v -> {
            if (eqpInfoEntity == null){
                return;
            }
            if (eqpInfoEntity.getTRACKOUT_PROCESS_CRR().equals("1")){
                if (tvProcess.getText().toString().equals("")){
                    showToast("请输入或扫描运输筐号",false);
                    return;
                }
            }
            submit();
        }
        );
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        View v = getCurrentFocus();
        if (v != null && v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (eqpInfoEntity != null) {
            if (!FreeApi_StringUtils.isEmpty(s.toString())) {
                int totalNum = eqpInfoEntity.getPRODUCTION_TOTAL_QUANTITY();
//                int defectNum = Integer.parseInt(s.toString().trim());
                int outputNum = Integer.parseInt(s.toString().trim());
                if (outputNum <= totalNum) {
//                    etOutputNum.setText(String.valueOf(totalNum - defectNum));
//                    qualifiedTxt.setText(getQualified(totalNum, defectNum));
                    defectNumTxt.setText(String.valueOf(totalNum - outputNum));
                    qualifiedTxt.setText(getQualified(totalNum, totalNum - outputNum));
                } else {
                    showToast("产出数量不能大于总数量！", false);
                    defectNumTxt.setText("");
                    qualifiedTxt.setText("");
                }
            } else {
                defectNumTxt.setText("");
                qualifiedTxt.setText("");
            }
        }


    }

    /**
     * 计算合格率
     *
     * @param totalNum  总数量
     * @param defectNum 不良数量
     * @return
     */
    private String getQualified(int totalNum, int defectNum) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format(((float) (totalNum - defectNum) / (float) totalNum) * 100);
        return result + "%";
    }

    @OnClick({R.id.tvAdd,R.id.tvProcess})
    public void onViewClicked(View v) {
        if (v.getId() == R.id.tvAdd){
            EqpInfoEntity.RejectQt rejectQt = new EqpInfoEntity.RejectQt("",0,0);
            defectListAdapter.addData(rejectQt);
//            defectListAdapter.notifyDataSetChanged();
        }else if (v.getId() == R.id.tvProcess){
            showSpanDialog(PROCESS_TRACK_OUT_CRR,"请输入或扫描运输筐号");
        }

    }

    @Override
    protected void EQPReplaceSuccess(int tag, String content) {
        if (tag == PROCESS_TRACK_OUT_CRR){
            tvProcess.setText(content);
        }
    }
}
